#!/usr/bin/python3

import vcard

import sys
import os
import getopt

__veriosn__ = "Indev"

shortopts = '-f:-h-o:-O:-v-V'
longopts = ['help', 'inputfile=', 'outputfile=',
            'overwrite=', 'version', 'verbose']

d_fin = 'vcard.xlsx'
d_fout = 'vcard.vcf'


def print_help():
    print("Usage: "+str(sys.argv[0])+" [OPTION] [FILE] [FILE]")
    print("Options: ")
    print(" "*9+"-f, --inputfile=inputfile")
    print(" "*13+"Specify the file you want to convert, ./vcard.xlsx as default.")
    print("")
    print(" "*9+"-o, --outputfile=outputfile")
    print(" "*13+"Specify the file you want to store the result, ./vcard.vcf as default.")
    print("")
    print(" "*9+"-O, --overwrite=outputfile")
    print(" "*13+"Specify the file you want to store the result, ./vcard.vcf as default.")
    print(" "*13+"If the target already exists, overwrite it!")
    print("")
    print(" "*9+"-v, --verbose")
    print(" "*13+"Verbosely list conversion processed.")
    print("")
    print("Or     \""+str(sys.argv[0])+" -h|--help\" to print this help")
    print("       \""+str(sys.argv[0]) +
          " -V|--version\" to print script version")
    print("")
    print("Default input file is \"./vcard.xlsx\"")
    print("Default output file is \"./vcard.vcf\"\n")

opts, noneed = getopt.getopt(
    sys.argv[1:], shortopts, longopts)

opt1 = opts[0]
if opt1[0] in ('-h', '--help'):
    print('Version: '+__veriosn__)
    print_help()
    sys.exit()
elif opt1[0] in('-V', '--version'):
    print('Version: '+__veriosn__)
    sys.exit()

needverbose = False
isoverwrite = False
fin = None
fout = None

for opt_name, opt_value in opts:

    if opt_name in ('-h', '--help'):
        continue  # just ignore it
    elif opt_name in('-V', '--version'):
        continue  # ignore it too
    elif opt_name in('-v', '--verbose'):
        needverbose = True
    elif opt_name in ('-f', '--inputfile'):
        fin = opt_value
    elif opt_name in ('-o', '--outputfile'):
        fout = opt_value
    elif opt_name in ('-O', '--overwrite'):
        fout = opt_value
        isoverwrite = True
    else:
        print("Unknow option(s)")
        print_help()
        sys.exit()

if not fin:
    fin = d_fin

if not fout:
    fout = d_fout

if not isoverwrite and os.path.isfile(fout):
    print("Warning: Outputfile already existed!")
    print(''*9+"Use \"[-O|--overwrite outputfile]\" to overwrite a file.")
    sys.exit()

contact1 = vcard.VCARD()
contact1.convert(fin, fout, verbose=needverbose)
